package cn.itsource.user.service.impl;

import cn.itsource.basic.service.impl.BasicServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.LoginInfoMapper;
import cn.itsource.user.service.ILoginInfoService;
import cn.itsource.user.service.IUserService;
import cn.itsource.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginInfoServiceImpl extends BasicServiceImpl<LoginInfo> implements ILoginInfoService {

    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    //做登录的逻辑
    @Override
    public AjaxResult login(String username, String password) {
        //1.验证 数据的合法性
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw  new RuntimeException("用户名或密码不能为空");
        }
        //2.根据username 去数据库匹配数据
        LoginInfo loginInfo =  loginInfoMapper.login(username);
        if (loginInfo==null){
            throw  new RuntimeException("用户名或密码错误");
        }
        if (loginInfo.getDisable()==-1){
            throw  new RuntimeException("账号异常，请联系客服");
        }
        //验证密码的正确性
        String salt = loginInfo.getSalt();//加密的盐
        //比较两次加密后的密文是否一致
        if(!loginInfo.getPassword().equals(MD5Utils.encrypByMd5(password+salt))){
            throw  new RuntimeException("用户名或密码错误");
        }
        //登录成功  把当前的登录用户放到redis 设置过期时间 30分钟
        //1.生成一个 token  （本质就是一个字符串）
        String token = UUID.randomUUID().toString();
        //2.放到redis
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        //3.把token返回给前端用户，把当前的登录用户返回给前端
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //为了安全 把salt和password抹除
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo", loginInfo);
        //返回给前端用户
        return AjaxResult.me().setResultObj(map);
    }
}
